<template>
  <el-dialog
      v-model="showDialog"
      :title="title"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :draggable="true"
      @close="handleClose"
      @closed="handleClosed"
  >
    <el-upload
        class="upload-dialog"
        :show-file-list="false"
        action=""
        :http-request="handleUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
      <el-icon v-else class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>
    <template #footer>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
      <el-button type="danger" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {ref, watch} from "vue";
import {Plus} from '@element-plus/icons-vue'
import {uploadFileReq} from "@/api/common/common.ts";

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '上传图片'
  }
})

const emits = defineEmits(['handleConfirm', 'handleClose', 'handleClosed'])

const showDialog = ref(props.showDialog)
watch(() => props.showDialog, (val: boolean) => {
  showDialog.value = val
})

const fileResult = ref<any>(null)

const imageUrl = ref<string>('')

const handleConfirm = () => {
  emits('handleConfirm', fileResult.value)
  emits('handleClosed', false);
}

const handleClose = () => {
  emits('handleClose', false)
}

const handleClosed = () => {
  emits('handleClosed', false)
}

const handleUpload = async (params: any) => {
  const formData = new FormData();
  formData.append('file', params.file)
  fileResult.value = await uploadFileReq(formData)
}

</script>

<style scoped>
.upload-dialog {
  width: 100px;
  height: 100px;
}

</style>